package tech.tongyu.bob.demo.proxy.cglibproxy.proxy;

import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;

import java.lang.reflect.Method;

public class TransactionProxy implements MethodInterceptor {
    private final Object target;

    public TransactionProxy(Object target) {
        this.target = target;
    }

    @Override
    public Object intercept(Object obj, Method method, Object[] args, MethodProxy proxy) throws Throwable {
        Object result = null;
        try {
            System.out.println("开启事务...");
            // 开启事务的逻辑

            result = proxy.invokeSuper(obj, args); // 调用实际的业务方法

            System.out.println("提交事务...");
            // 提交事务的逻辑
        } catch (Exception e) {
            System.out.println("回滚事务...");
            // 回滚事务的逻辑
            throw e;
        }
        return result;
    }

    @SuppressWarnings("unchecked")
    public static <T> T createProxy(Class<T> targetClass) {
        Enhancer enhancer = new Enhancer();
        enhancer.setSuperclass(targetClass);
        enhancer.setCallback(new TransactionProxy(null));
        return (T) enhancer.create();
    }
}
